-- appends a 9GAG/FunnyJunk-esque prefabricated watermark to any provided image
-- usage: facemark.lua input.png output.png
-- example: facemark.lua sobotniknude564.jpg poopooimage.png

local function usage()
  print( "Usage:")
  print( " lua facemark.lua <input file>" )
  print( " lua facemark.lua <input file> <output file>" )
end

local supportedFileExts = {
	"jpeg",
	"jpg",
	"png",
	"gif"
}

-- Andrew; Here's some neat path name separation used for GD input
-- (See: http://stackoverflow.com/questions/5243179/what-is-the-neatest-way-to-split-out-a-path-name-into-its-components-in-lua)
local function getExt( path )
	local ext = ""
	for _, str in pairs( { string.match( path, "(.-)([^\\]-([^%.]+))$" )} ) do
		ext = str
	end
	return ext
end

local function validateFileExt( ext )
	ext = string.lower( ext )
	for _, v in ipairs( supportedFileExts ) do
		if ( ext == v ) then
			return
		end
	end

	print( "ERROR: Invalid input file type!" )
	os.exit( 1 )
end

local inputFileName = arg[ 1 ]
local inputFileExt = ""

if ( inputFileName == nil ) then
	usage()
	os.exit( 1 )
end

inputFileExt = getExt( inputFileName )
validateFileExt( inputFileExt )

local outputFileName = arg[ 2 ]
local outputFileExt = "png"

if ( outputFileName == nil ) then
	outputFileName = "output.png"
end

outputFileExt = getExt( outputFileName )
validateFileExt( outputFileExt )

local gd = require( "gd" )

local createFromFuncs = {
	jpeg = gd.createFromJpeg,
	jpg = gd.createFromJpeg,
	png = gd.createFromPng,
	gif = gd.createFromGif
}

local createFromFunc = createFromFuncs[ inputFileExt ]

local input = createFromFunc( inputFileName )
if ( not input ) then
	print( "ERROR: " .. inputFileName .. " bad " .. inputFileExt .. " data." )
	os.exit( 1 )
end
local width, height = input:sizeXY()

local output = gd.createTrueColor( width, height + 32 )
output:copy( input, 0, 0, 0, 0, width, height )

local watermark = gd.createFromPng( "watermark.png" )

-- Background
local widthCovered = 0
while ( widthCovered < width ) do
	output:copy( watermark, widthCovered, height, 0, 0, 12, 32 )
	widthCovered = widthCovered + 12
end

-- Logo
output:copy( watermark, 0, height, 0, 32, 76, 32 )

-- URL
output:copy( watermark, width - 136 - 10, height + 10, 0, 64, 136, 13 )

if ( outputFileExt == "jpeg" ) then
	output:jpeg( outputFileName, 100 )
	os.exit( 0 )
elseif ( outputFileExt == "jpg" ) then
	output:jpeg( outputFileName, 100 )
	os.exit( 0 )
elseif ( outputFileExt == "png" ) then
	output:png( outputFileName )
	os.exit( 0 )
elseif ( outputFileExt == "gif" ) then
	output:gif( outputFileName )
	os.exit( 0 )
end
